package com.caijing.caijingxueyuanxd.service;


import com.caijing.caijingxueyuanxd.config.WebConfig;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ImageService {
    private final WebConfig webConfig;

    public ImageService(WebConfig webConfig) {
        this.webConfig = webConfig;
    }

    /**
     * 获取所有图片的URL路径
     * @return 图片路径列表
     */
    public List<String> getAllImagePaths() throws IOException {
        Resource[] resources = webConfig.getImageResources();
        List<String> imagePaths = new ArrayList<>();

        for (Resource resource : resources) {
            // 转换为可访问的URL路径
            String urlPath = resource.getURL().toString();
            // 提取/public路径后的部分（去掉协议和域名）
            String relativePath = urlPath.substring(urlPath.indexOf("/static/"));
            imagePaths.add("http://localhost:8080" + relativePath);
        }

        return imagePaths;
    }

    /**
     * 获取图片详情（文件名+URL）
     * @return 图片信息列表
     */
    public List<Map<String, String>> getImageDetails() throws IOException {
        Resource[] resources = webConfig.getImageResources();
        List<Map<String, String>> images = new ArrayList<>();

        for (Resource resource : resources) {
            Map<String, String> imageInfo = new HashMap<>();
            imageInfo.put("fileName", resource.getFilename());
            imageInfo.put("url", resource.getURL().toString());
            images.add(imageInfo);
        }

        return images;
    }
}
